//
//  SCFileManager.m
//  Shuaiche
//
//  Created by yujunyang on 2021/5/8.
//  Copyright © 2021 ShuaiChe. All rights reserved.
//

#import "SCFileManager.h"
#import "SCImageUploadManager.h"
#include <CommonCrypto/CommonDigest.h>
#import <AFNetworking.h>

@implementation SCFileManager

+ (NSString *)cachesFilePath:(NSUInteger)uploadType{
    NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) firstObject];
    NSString *dataFilePath = [cachesDir stringByAppendingPathComponent:(uploadType==0)?@"maintainreport":@"testreport"];
    return dataFilePath;
}

+ (NSString *)storePdfFile:(NSString *)fileName uploadType:(NSUInteger)uploadType fileData:(NSData *)fileData{
    
    NSString *dataFilePath = [SCFileManager cachesFilePath:uploadType];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:dataFilePath isDirectory:&isDir];
    
    if (!(isDir && existed)) {
        // 在Document目录下创建一个archiver目录
        [fileManager createDirectoryAtPath:dataFilePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *filePath = [dataFilePath stringByAppendingPathComponent:fileName];
    [fileData writeToFile:filePath atomically:YES];
    
    NSString *md5Path = [SCFileManager md5FileRename:filePath];
    return md5Path;
}

/**
 对文件重命名
 
 @param filePath 旧路径
 @return MD5文件名称
 */
+ (NSString *)md5FileRename:(NSString *)filePath{
    
    NSString *lastPathComponent = [NSString new];
    //获取文件名： 文件.pdf
    lastPathComponent = [filePath lastPathComponent];
    //获取后缀：.pdf
    NSString *pathExtension = [filePath pathExtension];
    //用传过来的路径创建新路径 首先去除文件名
    NSString *pathNew = [filePath stringByReplacingOccurrencesOfString:lastPathComponent withString:@""];
    NSString *MD5Str = [SCFileManager getFileMD5StrFromPath:filePath];
   
    NSString *moveToPath = [NSString stringWithFormat:@"%@%@.%@",pathNew,MD5Str,pathExtension];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //通过移动该文件对文件重命名
    BOOL isSuccess = [fileManager moveItemAtPath:filePath toPath:moveToPath error:nil];
    if (isSuccess) {
        NSLog(@"rename success");
    }else{
        NSLog(@"rename fail");
    }
    return moveToPath;
}

/** 获取文件的md5值*/
+ (NSString *)getFileMD5StrFromPath:(NSString *)path{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path isDirectory:nil]){
        
        NSData *data = [NSData dataWithContentsOfFile:path];
        unsigned char digest[CC_MD5_DIGEST_LENGTH];
        CC_MD5( data.bytes, (CC_LONG)data.length, digest );
        NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
        for( int i = 0; i < CC_MD5_DIGEST_LENGTH; i++ ){
            [output appendFormat:@"%02x", digest[i]];
        }
        return output;
    }else{
        return @"";
    }
}

//传入本地文件路径 通过地址拼接 访问服务器是否已经存在该文件
+ (void)pdfExistUploaded:(NSString *)filePath uploadType:(NSUInteger)uploadType completion:(void(^)(NSString *fileURL))handleBlock{
    
    NSString *md5Name = [filePath lastPathComponent];
    NSString *fileURL = [NSString stringWithFormat:@"%@/%@",[SCImageUploadManager pdfFilePath:uploadType],md5Name];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/pdf", nil];

    [manager GET:sc_url_img(fileURL) parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //服务器存在该文件 清空本地文件夹 返回url
        [SCFileManager deletePDFFile:uploadType];
        handleBlock(sc_url_img(fileURL));
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        handleBlock(nil);
    }];
}
//上传成功 或者 服务器存在该问价 执行删除操作
+ (void)deletePDFFile:(NSUInteger)uploadType{
    
    NSString *dataFilePath = [SCFileManager cachesFilePath:uploadType];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // 文件夹删除
    [fileManager removeItemAtPath:dataFilePath error:nil];
}

@end
